package com.bbc.yuntun.common.utils.http;


import jakarta.servlet.ServletRequest;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;


/**
 * 通用http工具封装
 *
 * @author ruoyi
 */
public class HttpHelper {

    /**
     *  LOG 日志 打印一些测试信息等
     */
    private static final Logger LOG = LoggerFactory.getLogger(HttpHelper.class);

    /**
     * 获取请求主体内容
     *
     * @param request HTTP请求
     * @return 请求主体内容
     */
    public static String getBodyString(ServletRequest request) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        try (InputStream inputStream = request.getInputStream()) {
            reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            LOG.warn("getBodyString出现问题！");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    LOG.error(ExceptionUtils.getMessage(e));
                }
            }
        }
        return sb.toString();
    }
}
